import * as THREE from "three";

const RADIUS = 4;
const SPEED = .01;

export default class Ferris {
  constructor() {
    this.chairModels = [];
    this.bodyModel = new THREE.Mesh();
    this.main = new THREE.Group();
    this.chairs = [];
    this.rotation = 0;
  }

  add(mesh) {
    if (mesh.userData.name === "ferris-chair") {
      this.chairModels.push(mesh);
    }
    if (mesh.userData.name === "ferris-rotation") {
      this.bodyModel = mesh;
    }
  }

  build() {
    this.center = this.bodyModel.position.clone();
    this.bodyModel.position.set(0, 0, 0);
    this.main.add(this.bodyModel);
    this.main.position.copy(this.center);

    const chair = new THREE.Group();
    this.chairModels.map((model) => {
      model.position.set(0, 0, 0);
      chair.add(model);
    });
    this.main.add(chair);

    const nums = 12;
    this.chairs.push(chair);
    for (let i = 1; i < nums; i++) {
      const n = chair.clone();
      n.position.set(0, 0, 0);
      this.chairs.push(n);
      this.main.add(n);
    }
  }

  setChairsPosition() {
    for (let i = 0; i < this.chairs.length; i++) {
      const chair = this.chairs[i];
      const rand = Math.PI * 2 / this.chairs.length * i - this.rotation;
      const x = RADIUS * Math.cos(rand);
      const z = RADIUS * Math.sin(rand);
      chair.position.x = x;
      chair.position.z = z;
    }
  }

  update() {
    this.rotation += SPEED;
    this.bodyModel.rotation.y = this.rotation;
    this.setChairsPosition();
  }
}